package com.nearby.demand.ui;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.auto.layout.lib.AutoLayoutActivity;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.nearby.demand.R;
import com.nearby.demand.presenter.LoginPersenter;
import com.nearby.demand.presenter.LoginPersenterImpl;
import com.nearby.demand.ui.view.LoginView;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.utils.SPUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by IME on 2015/12/28.
 */
public class UiLogin extends AutoLayoutActivity implements LoginView {
    @Bind(R.id.et_log_user_name)
    EditText etLogUserName;
    @Bind(R.id.et_password)
    EditText etPassword;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.tv_registered_user)
    TextView tvRegisteredUser;
    LoginPersenter persenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_login);
        persenter = new LoginPersenterImpl(this);
        ButterKnife.bind(this);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void startMain() {
        final String name = etLogUserName.getText().toString().trim();
        final String password = etPassword.getText().toString().trim();
        EMChatManager.getInstance().login(name, password, new EMCallBack() {
            @Override
            public void onSuccess() {
                KLog.i("onSuccess");
                SPUtil.putAndApply(UiLogin.this, "is_login", true);
                SPUtil.putAndApply(UiLogin.this, "user_name", name);
                SPUtil.putAndApply(UiLogin.this, "password", password);
                //群组
                EMGroupManager.getInstance().loadAllGroups();
                //会话
                EMChatManager.getInstance().loadAllConversations();
                Intent intent = new Intent(UiLogin.this,
                        UiMain.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int i, String s) {
                KLog.i("onError");
                SPUtil.putAndApply(UiLogin.this, "is_login", false);
            }

            @Override
            public void onProgress(int i, String s) {
                KLog.i("onProgress");
            }
        });

    }

    @OnClick(R.id.btn_login)
    public void login() {
//        persenter.validateCredentials("", "");
        startMain();
    }
}
